#!/usr/bin/perl
# 2014/05/16 Read data of BED file and grouped to use with average_enrichment_at_gene.pl

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 6 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [input BED file] -n [number of groups] -o [output BED file]\n";
}

my %opt;
getopts("i:o:n:", \%opt);
my $FILE_in = $opt{i};
my $FILE_out = $opt{o};
my $NUMBER_OF_GROUPS = $opt{n};

my $PREFIX_OF_GROUP_NAME = 'GROUP_';


my @VALUES;
my %DATA;
my $fh_in = IO::File->new($FILE_in) or die "cannot open $FILE_in: $!";
while($_ = $fh_in->getline()){
	s/\r?\n//;
	my ($chr, $start, $end, $name, $value, $direction) = split /\t/;
	push @VALUES, $value;
	$DATA{"$chr\t$start\t$end\t$name\t$direction"} = $value;
}
$fh_in->close();


my $NUMBER_IN_EACH_CATEGORY = @VALUES / $NUMBER_OF_GROUPS;
if($NUMBER_IN_EACH_CATEGORY  !=  int($NUMBER_IN_EACH_CATEGORY)){
	$NUMBER_IN_EACH_CATEGORY = int($NUMBER_IN_EACH_CATEGORY) + 1;
}

my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
my $group_number = 1;
my $count = 0;
foreach my $key ( sort {$DATA{$b} <=> $DATA{$a}} keys %DATA){
	$count++;
	if($count > $NUMBER_IN_EACH_CATEGORY){
		$group_number++;
		$count = 0;
	}
	my $group_name = $PREFIX_OF_GROUP_NAME . $group_number;
	my ($chr, $start, $end, $name, $direction) = split /\t/, $key;
	$fh_out->print("$chr\t$start\t$end\t$name\t$group_name\t$direction\n");
}
$fh_out->close();




